'use strict';

const Controller = require('egg').Controller;
// const WXBizDataCrypt = require('../lib/function/WXBizDataCrypt');

const signInRule = {
  code: 'string',
  encryptedData: 'string',
  iv: 'string'
};

class AuthController extends Controller {
  async signIn () {
    this.ctx.validate(signInRule);

    const shopId = this.ctx.request.body.shopId ? this.ctx.request.body.shopId : 10004;
    const code = this.ctx.request.body.code;
    const encryptedData = this.ctx.request.body.encryptedData;
    const iv = this.ctx.request.body.iv;

    // let token;
    // const result = await this.app.curl('https://api.weixin.qq.com/sns/jscode2session?appid=wx7ee13f9c800d9961&secret=477b0ced47d4252b0fffe81395ca3535&js_code=' + code + '&grant_type=authorization_code', {
    //   dataType: 'json'
    // });

    // var appId = 'wx7ee13f9c800d9961';

    // var pc = new WXBizDataCrypt(appId, result.data.session_key);

    // var data = pc.decryptData(encryptedData, iv);

    // const user = await this.app.api.users.signIn(data.unionId, shopId);
    const user = await this.service.auth.signIn(shopId, code, encryptedData, iv);

    console.log(user);

    const imgHost = this.app.config.qiniu.bucket.subImg.host;

    user.avatarUrl = imgHost + user.avatar;

    const token = this.app.jwt.sign({ id: user.id }, this.app.config.jwt.secret, { expiresIn: '30d' });
    this.ctx.body = {
      token,
      user
    };
  }
}

module.exports = AuthController;
